/*
	使用说明:
	right为tip出现的方向, 还可能为left, top, bottom
*/
define(
	'apm/ui/formtip',
	[],
	function () {
		var FormTooltipMixin = Ember.Mixin.create({
			tooltip: null,

			tooltipDir: "right",

			init: function(){
				this._super();

				if (this.tooltip) {
					this._createTooltip();
					this.on("focusIn", this._focusIn4tip);
					this.on("focusOut", this._focusOut4tip);
					this.on("willDestroyElement", this, this._destroyTooltip);
				}
			},
			_createTooltip: function(){
				var $tooltip = $('<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>');
				this.$tooltip = $tooltip;
				$tooltip
					.attr("id", this.elementId+"Tooltip")
					.addClass(this.tooltipDir)
					.appendTo("body")
					.find(".tooltip-inner")
					.html(this.tooltip);
			},

			_destroyTooltip: function(){
				this.$tooltip.remove();
				this.$tooltip = undefined;
			},

			_focusIn4tip: function(){
				this._showFormItemTip();
			},
			_focusOut4tip: function(){
				this.$tooltip.hide().removeClass("in");
			},
			_showFormItemTip: function(){
				var $target = this.$(),
					$targetTip = this.$tooltip,
					tarPos, tarTipPos;

				if( $targetTip[0] ){
					tarPos = $.extend({}, $target.offset(), {
						width: $target.outerWidth(),
						height: $target.outerHeight()
					});

					tarTipPos = this._computeTipPos($targetTip, tarPos);

					$targetTip.css(tarTipPos).addClass("in").show();
				}
			},
			_computeTipPos: function($targetTip, tarPos){
				var tp, tarTipHeight;

				$targetTip.css({
					top: -100,
					left: 0
				}).show();

				tarTipHeight = $targetTip.outerHeight();

				$targetTip.hide();

				if( $targetTip.hasClass("bottom") ){
					tp = {top: tarPos.top + tarPos.height, left: tarPos.left};
				} else if( $targetTip.hasClass("top") ){
					tp = {top: tarPos.top - tarTipHeight, left: tarPos.left};
				} else if( $targetTip.hasClass("left") ){
					tp = {top: tarPos.top + tarPos.height / 2 - tarTipHeight / 2, left: tarPos.left - actualWidth};
				} else if( $targetTip.hasClass("right") ){
					tp = {top: tarPos.top + tarPos.height / 2 - tarTipHeight / 2, left: tarPos.left + tarPos.width};
				}
				return tp;
			}
		});

		Ember.TextSupport.reopen(FormTooltipMixin);
		Ember.Select.reopen(FormTooltipMixin);
		Ember.Checkbox.reopen(FormTooltipMixin);

		return FormTooltipMixin;
	}
);